package com.com.shared.domain;

import org.junit.After;
import org.junit.Before;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyOpts;

public class ObjectifyTestBase {

    
    /** */
    protected ObjectifyFactory fact;
    
    /** */
    private final LocalServiceTestHelper helper =
                    new LocalServiceTestHelper(
                                    new LocalDatastoreServiceTestConfig(),
                                    new LocalMemcacheServiceTestConfig(),
                                    new LocalTaskQueueTestConfig());
    /** */
    @Before()
    public void setUp()
    {
            this.helper.setUp();
            
            this.fact = new ObjectifyFactory() {
                    @Override
                    public Objectify begin(ObjectifyOpts opts)
                    {
                            // This can be used to enable/disable the memory cache globally.
                            opts.setGlobalCache(true);
                            
                            // This can be used to enable/disable the session caching objectify
                            // Note that it will break several unit tests that check for transmutation
                            // when entities are run through the DB (ie, unknown List types become
                            // ArrayList).  These failures are ok.
                            opts.setSessionCache(true);
                            
                            return super.begin(opts);
                    }
            };
            
            this.fact.register(Car.class);
    }

    /** */
    @After
    public void tearDown()
    {
            this.helper.tearDown();
    }
    
    /** Utility methods that puts and immediately gets an entity */
    protected <T> T putAndGet(T saveMe)
    {
            Objectify ofy = this.fact.begin();
            
            Key<T> key = ofy.put(saveMe);

            try
            {
                    Entity ent = ofy.getDatastore().get(fact.getRawKey(key));
                    System.out.println(ent);
            }
            catch (EntityNotFoundException e) { throw new RuntimeException(e); }

            return ofy.find(key);
    }
}